import 'dart:math';

import 'package:acgn_pioneer/pages/reader/reader_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

import '../../public.dart';

/// 阅读页
class ReaderPageMain extends StatefulWidget {
  /// 入口漫画id
  final int comicId;

  /// 入口章节id
  final int chapterId;

  /// 是否嵌套在弹窗中
  final bool isPopNested;

  final List<dynamic> comicIds; // 漫画数据

  ReaderPageMain(
      {Key key,
      this.comicId,
      this.chapterId,
      this.isPopNested = false,
      this.comicIds = const []})
      : super(key: key);

  @override
  ReaderPageMainState createState() => ReaderPageMainState();

  static ReaderPageMainState of(BuildContext context) {
    assert(context != null);
    final ReaderPageMainState result =
        context.findAncestorStateOfType<ReaderPageMainState>();
    return result;
  }
}

class ReaderPageMainState extends State<ReaderPageMain> {
  int currentPageIndex = 0; // 当前漫画序号
  double touchS = 0;
  double touchE = 0;
  bool keepPage = false; // 内部竖向滚动时，不响应主页左右滑动监听

  int preLoadPage = 3;
  double screenWidth = ScreenUtil.getInstance().screenWidth;
  ScrollController controller;
  List<dynamic> comicIds = []; // 漫画数据

  @override
  void initState() {
    super.initState();

    getMainData();
  }

  doKeepPage() {
    keepPage = true;
  }

  /// 子组件调用此方法，用于向下翻页（阅读到漫画末尾时，加载下一部漫画）
  toNextComicPage() {
    currentPageIndex += 1;
    controller.jumpTo(currentPageIndex * screenWidth);
  }

  initOffset() {
    var index = comicIds.indexOf(widget.comicId);
    index = index == -1 ? 0 : index;
    currentPageIndex = index;
    controller = new ScrollController(initialScrollOffset: index * screenWidth);
  }

  getMainData() async {
    // comicIds = [105984, 108070, 107529, 107530, 107024, 108052];
    if (widget.comicIds.length > 0) {
      comicIds = widget.comicIds;
    } else {
      comicIds = await HomeService().getHomeData();
    }
    initOffset();
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LoadingComponent(
        backgroundColor: Color(0xff1B1B26),
        maintainState: true,
        show: comicIds.length == 0,
        child: Listener(
            onPointerDown: (event) {
              touchS = event.position.dx;
            },
            onPointerUp: (event) {
              touchE = event.position.dx;
              pageMove();
            },
            onPointerMove: onPointerMove,
            child: ListView.builder(
              physics: ClampingScrollPhysics(),
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemExtent: screenWidth,
              cacheExtent: screenWidth * preLoadPage,
              controller: controller,
              itemCount: comicIds.length,
              itemBuilder: (context, index) {
                return ReaderPage(
                    isPopNested: widget.isPopNested,
                    comicId: comicIds[index],
                    chapterId: widget.comicId == comicIds[index]
                        ? widget.chapterId
                        : null);
              },
            )));
  }

  void onPointerMove(event) {
    if (keepPage) {
      animationPage();
    }
  }

  // 滑页
  void pageMove() {
    var diff = touchE - touchS;
    if (diff.abs() <= 50 || keepPage) {
      animationPage();
      keepPage = false;
      return;
    }
    var page = diff > 0 ? currentPageIndex - 1 : currentPageIndex + 1;
    page = max(page, 0);
    page = min(page, comicIds.length - 1);
    if (page != currentPageIndex) {
      currentPageIndex = page;
      animationPage();
    }
  }

  void animationPage({int microseconds = 800}) {
    controller.animateTo(currentPageIndex * screenWidth,
        duration: new Duration(microseconds: microseconds), curve: Curves.ease);
  }
}
